package xyz.lwm.lazycat.vertx;

import xyz.lwm.lazycat.utility.PathUtil;
import xyz.lwm.lazycat.utility.StringUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import static xyz.lwm.lazycat.utility.StrPool.STR_LEFT_BRACE;
import static xyz.lwm.lazycat.utility.StrPool.STR_RIGHT_BRACE;
import static xyz.lwm.lazycat.utility.StrPool.STR_SLASH;

/**
 * vertx 参数处理类
 *
 * @author lwm
 */
abstract class VertxParamUtil {

    public static String encode(String str, Charset charset) {
        try {
            return URLEncoder.encode(str, charset.toString());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String, String> parsePathParams(String routePath, String requestPath) {
        if (StringUtil.isBlank(routePath) || StringUtil.isBlank(requestPath) ||
                !routePath.contains(STR_LEFT_BRACE) || routePath.equals(requestPath)) {
            return Collections.emptyMap();
        }

        Map<String, String> pathParams = new LinkedHashMap<>();

        routePath = PathUtil.normalizePath(routePath);
        requestPath = PathUtil.normalizePath(requestPath);
        String[] routeStrArr = routePath.split(STR_SLASH);
        String[] requestStrArr = requestPath.split(STR_SLASH);
        for (int i = 0; i < routeStrArr.length; i++) {
            String routeStr = routeStrArr[i];
            if (routeStr.startsWith(STR_LEFT_BRACE) && routeStr.endsWith(STR_RIGHT_BRACE)) {
                String name = routeStr.substring(1, routeStr.length() - 1);
                String value = requestStrArr[i];
                pathParams.put(name, value);
            }
        }
        return pathParams;
    }

}
